package gui.item;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import core.CoreFacade;
import core.Item;

import gui.common.*;

/**
 * Controller class for the edit item view.
 */
public class EditItemController extends Controller 
										implements IEditItemController {
	
	private CoreFacade core;
	private boolean canEdit;
	private String barcode;
	private String description;
	private Date date;
	private Item item;
	/**
	 * Constructor.
	 * 
	 * @param view Reference to edit item view
	 * @param target Item that is being edited
	 */
	public EditItemController(IView view, ItemData target) {
		super(view);
		core = CoreFacade.getInstance();
		
		item = (Item)target.getTag();
		
		canEdit = true;
		
		barcode = target.getBarcode();
		
		description = item.getProduct().getDescription();
		
		date = target.getEntryDate();
		
		construct();
	}

	//
	// Controller overrides
	//
	
	/**
	 * Returns a reference to the view for this controller.
	 * 
	 * {@pre None}
	 * 
	 * {@post Returns a reference to the view for this controller.}
	 */
	@Override
	protected IEditItemView getView() {
		return (IEditItemView)super.getView();
	}

	/**
	 * Sets the enable/disable state of all components in the controller's view.
	 * A component should be enabled only if the user is currently
	 * allowed to interact with that component.
	 * 
	 * {@pre None}
	 * 
	 * {@post The enable/disable state of all components in the controller's view
	 * have been set appropriately.}
	 */
	@Override
	protected void enableComponents() 
	{
		getView().enableOK(canEdit);
		getView().enableBarcode(false);
		getView().enableDescription(false);
	}

	/**
	 * Loads data into the controller's view.
	 * 
	 *  {@pre None}
	 *  
	 *  {@post The controller has loaded data into its view}
	 */
	@Override
	protected void loadValues() 
	{
		getView().setBarcode(barcode);
		getView().setDescription(description);
		getView().setEntryDate(date);
	}

	//
	// IEditItemController overrides
	//

	/**
	 * This method is called when any of the fields in the
	 * edit item view is changed by the user.
	 */
	@Override
	public void valuesChanged() 
	{
		date = getView().getEntryDate();
		try{
		canEdit = core.isValidDate(date);
		}catch(Exception e){canEdit=false;}
		enableComponents();
	}
	
	/**
	 * This method is called when the user clicks the "OK"
	 * button in the edit item view.
	 */
	@Override
	public void editItem() 
	{
		Calendar cal =new GregorianCalendar();
		cal.setTime(date);
		try {
			core.editItem(item, cal);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

